package com.freedom.mediaplayer.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.freedom.mediaplayer.R;
import com.freedom.mediaplayer.app.AppConstant;
import com.freedom.mediaplayer.entity.Music;
import com.freedom.mediaplayer.until.DataUtil;
import com.freedom.mediaplayer.until.ImageUtil;
import com.freedom.mediaplayer.until.MusicUntil;

public class MediaCenter extends BaseFragment implements OnClickListener {
	private TextView artistMusic;
	private TextView currentProgress;// 当前进度消耗的时间
	private TextView finalProgress;// 歌曲时间
	private ImageView musicAblumReflection;
	private ImageView musicAlbum;
	private SeekBar musicProgressBar;// 歌曲进度
	private Button nextMusic;// 下一首
	private Button playMusic;
	private Button previousMusic;// 上一首
	private Button repeatMusic;
	private Button shuffleMusic;// 随机播放
	private TextView titleMusic;
	private int currentTime; // 当前歌曲播放时间
	private int duration; // 歌曲长度
	
	private int repeatState;
	private final int isCurrentRepeat = 1; // 单曲循环
	private final int isAllRepeat = 2; // 全部循环
	private final int isNoneRepeat = 3; // 无重复播放
	private boolean isPause; // 暂停
	private boolean isNoneShuffle; // 顺序播放
	private boolean isShuffle; // 随机播放
	// private List<Music> list;
	private PlayReceiver playReceiver;

	public static final String UPDATE_ACTION = "com.freedom.action.UPDATE_ACTION"; // 更新动作
	public static final String CTL_ACTION = "com.freedom.action.CTL_ACTION"; // 控制动作
	public static final String MUSIC_CURRENT = "com.freedom.action.MUSIC_CURRENT"; // 音乐当前时间改变动作
	public static final String MUSIC_DURATION = "com.freedom.action.MUSIC_DURATION";// 音乐播放长度改变动作
	public static final String MUSIC_PLAYING = "com.freedom.action.MUSIC_PLAYING"; // 音乐正在播放动作
	public static final String REPEAT_ACTION = "com.freedom.action.REPEAT_ACTION"; // 音乐重复播放动作
	public static final String SHUFFLE_ACTION = "com.freedom.action.SHUFFLE_ACTION";// 音乐随机播放动作
	public static final String SHOW_LRC = "com.freedom.action.SHOW_LRC"; // 通知显示歌词

	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		view = inflater.inflate(R.layout.fragment02, null);
		playMusic = (Button) view.findViewById(R.id.play_music);
		previousMusic = (Button) view.findViewById(R.id.previous_music);
		titleMusic = (TextView) view.findViewById(R.id.musicTitle);
		artistMusic = (TextView) view.findViewById(R.id.musicArtist);
		nextMusic = (Button) view.findViewById(R.id.next_music);
		repeatMusic = (Button) view.findViewById(R.id.repeat_music);
		shuffleMusic = (Button) view.findViewById(R.id.shuffle_music);
		musicProgressBar = (SeekBar) view.findViewById(R.id.audioTrack);
		currentProgress = (TextView) view.findViewById(R.id.current_progress);
		finalProgress = (TextView) view.findViewById(R.id.final_progress);
		musicAlbum = (ImageView) view.findViewById(R.id.iv_music_ablum);
		musicAblumReflection = (ImageView) view
				.findViewById(R.id.iv_music_ablum_reflection);
		return view;
	}

	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// list = MusicUntil.getMp3Infos(ct);
		repeatState = 3;
		setViewOnClickListener();
		musicProgressBar.setProgress(currentTime);
		musicProgressBar.setMax(duration);
		showArtwork(DataUtil.list.get(DataUtil.curPosition));
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		changStatue(DataUtil.list.get(DataUtil.curPosition));
		registerReceiver();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		ct.unregisterReceiver(this.playReceiver);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (DataUtil.isPlaying) {
			playMusic.setBackgroundResource(R.drawable.pause_selector);
		} else {
			playMusic.setBackgroundResource(R.drawable.play_selector);
		}
	}

	private void setViewOnClickListener() {
		playMusic.setOnClickListener(this);
		previousMusic.setOnClickListener(this);
		nextMusic.setOnClickListener(this);
		repeatMusic.setOnClickListener(this);
		shuffleMusic.setOnClickListener(this);
		musicProgressBar
				.setOnSeekBarChangeListener(new SeekBarChangeListener());
	}

	/**
	 * 播放音乐
	 */
	private void play() {
		playMusic.setBackgroundResource(R.drawable.pause_selector);
		repeatNone();
		Music temp = DataUtil.list.get(DataUtil.curPosition);
		Intent intent = new Intent();
		intent.setAction("com.freedom.media.MUSIC_SERVICE");
		intent.putExtra("url", temp.getUrl());
		// intent.putExtra("curPosition", DataUtil.curPosition);
		intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);
		ct.startService(intent);
	}

	public void repeatNone() {
		Intent intent = new Intent(CTL_ACTION);
		intent.putExtra("control", 3);
		ct.sendBroadcast(intent);
	}

	/**
	 * 上一首
	 */
	private void previous() {
		// TODO Auto-generated method stub
		DataUtil.curPosition = DataUtil.curPosition - 1;
		if (DataUtil.curPosition >= 0) {
			// SharedPrefencetUntil.setSharedPrefence(ct, DataUtil.curPosition);
			Music temp = DataUtil.list.get(DataUtil.curPosition);
			showArtwork(temp);
			changStatue(temp);
			Intent intent = new Intent();
			intent.setAction("com.freedom.media.MUSIC_SERVICE");
			// intent.putExtra("curPosition", DataUtil.curPosition);
			intent.putExtra("url", temp.getUrl());
			intent.putExtra("MSG", AppConstant.PlayerMsg.PRIVIOUS_MSG);
			ct.startService(intent);
		} else {
			DataUtil.curPosition = 0;
			Toast.makeText(ct, "没有上一首了", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 下一首
	 */
	public void nextMusic() {
		playMusic.setBackgroundResource(R.drawable.pause_selector);
		DataUtil.curPosition = DataUtil.curPosition + 1;
		if (DataUtil.curPosition <= DataUtil.list.size() - 1) {
			// SharedPrefencetUntil.setSharedPrefence(ct, DataUtil.curPosition);
			Music temp = DataUtil.list.get(DataUtil.curPosition);
			changStatue(temp);
			showArtwork(temp);
			Intent intent = new Intent();
			intent.setAction("com.freedom.media.MUSIC_SERVICE");
			intent.putExtra("url", temp.getUrl());
			// intent.putExtra("curPosition", curPosition);
			intent.putExtra("MSG", AppConstant.PlayerMsg.NEXT_MSG);
			ct.startService(intent);
		} else {
			DataUtil.curPosition = DataUtil.list.size() - 1;
			Toast.makeText(ct, "没有下一首了", Toast.LENGTH_SHORT).show();
		}
	}

	public void repeatOne() {
		Intent localIntent = new Intent("com.freedom.action.CTL_ACTION");
		localIntent.putExtra("control", 1);
		this.ct.sendBroadcast(localIntent);
	}

	public void shuffleMusic() {
		Intent localIntent = new Intent("com.freedom.action.CTL_ACTION");
		localIntent.putExtra("control", 4);
		this.ct.sendBroadcast(localIntent);
	}

	private void changStatue(Music music) {
		//System.out.println(music);
		titleMusic.setText(music.getTitle());
		artistMusic.setText(music.getArtist());
	}

	/**
	 * 显示专辑封面
	 */
	private void showArtwork(Music mp3Info) {
		Bitmap bm = MusicUntil.getArtwork(ct, mp3Info.getId(),
				mp3Info.getAlbumId(), true, false);
		// 切换播放时候专辑图片出现透明效果
		Animation albumanim = AnimationUtils.loadAnimation(ct,
				R.anim.album_replace);
		// 开始播放动画效果
		musicAlbum.startAnimation(albumanim);
		if (bm != null) {
			musicAlbum.setImageBitmap(bm); // 显示专辑封面图片
			musicAblumReflection.setImageBitmap(ImageUtil
					.createReflectionBitmapForSingle(bm)); // 显示倒影
		} else {
			bm = MusicUntil.getDefaultArtwork(ct, false);
			musicAlbum.setImageBitmap(bm); // 显示专辑封面图片
			musicAblumReflection.setImageBitmap(ImageUtil
					.createReflectionBitmapForSingle(bm)); // 显示倒影
		}

	}

	/**
	 * 全部循环
	 */
	private void repeatAll() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(CTL_ACTION);
		intent.putExtra("control", 2);
		ct.sendBroadcast(intent);
	}

	private void registerReceiver() {
		// 定义和注册广播接收器
		playReceiver = new PlayReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(UPDATE_ACTION);
		filter.addAction(MUSIC_CURRENT);
		filter.addAction(MUSIC_DURATION);
		ct.registerReceiver(playReceiver, filter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.play_music:
			Intent intent = new Intent();
			if (!DataUtil.isPlaying&&!this.isPause) {
				play();
				DataUtil.isPlaying = true;
			} else if (DataUtil.isPlaying) {
				playMusic.setBackgroundResource(R.drawable.play_selector);
				intent.setAction("com.freedom.media.MUSIC_SERVICE");
				intent.putExtra("MSG", 2);
				ct.startService(intent);
				DataUtil.isPlaying = false;
				isPause = true;  
			} else if (isPause) {
				playMusic.setBackgroundResource(R.drawable.pause_selector);
				intent.setAction("com.freedom.media.MUSIC_SERVICE");
				intent.putExtra("MSG", AppConstant.PlayerMsg.CONTINUE_MSG);
				ct.startService(intent);
				isPause = true;
				DataUtil.isPlaying = false;
			}
			break;
		case R.id.previous_music: // 上一首歌曲
			playMusic.setBackgroundResource(R.drawable.pause);
			isPause = false;
			DataUtil.isPlaying = true;
			previous();
			break;
		case R.id.next_music: // 下一首歌曲
			nextMusic();
			break;
		case R.id.repeat_music: // 重复播放音乐
			if (repeatState == isNoneRepeat) {
				repeatOne();
				shuffleMusic.setClickable(false); // 是随机播放变为不可点击状态
				repeatState = isCurrentRepeat;
			} else if (repeatState == isCurrentRepeat) {
				repeatAll();
				shuffleMusic.setClickable(false);
				repeatState = isAllRepeat;
			} else if (repeatState == isAllRepeat) {
				repeatNone();
				shuffleMusic.setClickable(true);
				repeatState = isNoneRepeat;
			}
			Intent intent1 = new Intent(REPEAT_ACTION);
			switch (repeatState) {
			case isCurrentRepeat: // 单曲循环
				repeatMusic.setBackgroundResource(R.drawable.repeat_current_selector);
				Toast.makeText(ct, R.string.repeat_current, Toast.LENGTH_SHORT).show();
				intent1.putExtra("repeatState", isCurrentRepeat);
				ct.sendBroadcast(intent1);
				break;
			case isAllRepeat: // 全部循环
				repeatMusic
						.setBackgroundResource(R.drawable.repeat_all_selector);
				Toast.makeText(ct, R.string.repeat_all, Toast.LENGTH_SHORT)
						.show();
				intent1.putExtra("repeatState", isAllRepeat);
				ct.sendBroadcast(intent1);
				break;
			case isNoneRepeat: // 无重复
				repeatMusic
						.setBackgroundResource(R.drawable.repeat_none_selector);
				Toast.makeText(ct, R.string.repeat_none, Toast.LENGTH_SHORT)
						.show();
				intent1.putExtra("repeatState", isNoneRepeat);
				break;
			}
			break;
		case R.id.shuffle_music: // 随机播放状态
			Intent shuffleIntent = new Intent(SHUFFLE_ACTION);
			if (isNoneShuffle) { // 如果当前状态为非随机播放，点击按钮之后改变状态为随机播放
				shuffleMusic.setBackgroundResource(R.drawable.shuffle_selector);
				Toast.makeText(ct, R.string.shuffle, Toast.LENGTH_SHORT).show();
				isNoneShuffle = false;
				isShuffle = true;
				shuffleMusic();
				repeatMusic.setClickable(false);
				shuffleIntent.putExtra("shuffleState", true);
				ct.sendBroadcast(shuffleIntent);
			} else if (isShuffle) {
				shuffleMusic
						.setBackgroundResource(R.drawable.shuffle_none_selector);
				Toast.makeText(ct, R.string.shuffle_none, Toast.LENGTH_SHORT)
						.show();
				isShuffle = false;
				isNoneShuffle = true;
				repeatMusic.setClickable(true);
				shuffleIntent.putExtra("shuffleState", false);
				ct.sendBroadcast(shuffleIntent);
			}
			break;
		}
	}

	/**
	 * 实现监听Seekbar的类
	 */
	private class SeekBarChangeListener implements OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			switch (seekBar.getId()) {
			case R.id.audioTrack:
				if (fromUser) {
					audioTrackChange(progress); // 鐢ㄦ埛鎺у埗杩涘害鐨勬敼鍙?
				}
				break;
			}
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {

		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}
	}

	/**
	 * 播放进度改变
	 * 
	 * @param progress
	 */
	private void audioTrackChange(int progress) {
		Intent intent = new Intent();
		Music temp = DataUtil.list.get(DataUtil.curPosition);
		intent.setAction("com.freedom.media.MUSIC_SERVICE");
		intent.putExtra("curPosition", DataUtil.curPosition);
		intent.putExtra("url", temp.getUrl());
		intent.putExtra("MSG", AppConstant.PlayerMsg.PROGRESS_CHANGE);
		intent.putExtra("progress", progress);
		ct.startService(intent);
	}

	/**
	 * 用来接收从service传回来的广播的内部类
	 */
	public class PlayReceiver extends BroadcastReceiver {

		private int currentTime;

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MUSIC_CURRENT)) {
				duration = intent.getIntExtra("duration", -1);
				currentTime = intent.getIntExtra("currentTime", -1);
				currentProgress.setText(MusicUntil.formatTime(currentTime));
				finalProgress.setText(MusicUntil.formatTime(duration));
				musicProgressBar.setProgress(currentTime);
			} else if (action.equals(MUSIC_DURATION)) {
				int duration = intent.getIntExtra("duration", -1);
				musicProgressBar.setMax(duration);
				finalProgress.setText(MusicUntil.formatTime(duration));
			} else if (action.equals(UPDATE_ACTION)) {
				// 获取Intent中的current消息，current代表当前正在播放的歌曲
				// DataUtil.curPosition = intent.getIntExtra("curPosition", -1);
				if (DataUtil.curPosition >= 0) {
					titleMusic.setText(DataUtil.list.get(DataUtil.curPosition)
							.getTitle());
					artistMusic.setText(DataUtil.list.get(DataUtil.curPosition)
							.getArtist());
					playMusic.setBackgroundResource(R.drawable.pause_selector);
					showArtwork(DataUtil.list.get(DataUtil.curPosition));
				}
				if (DataUtil.curPosition == 0) {
					playMusic.setBackgroundResource(R.drawable.pause_selector);
					showArtwork(DataUtil.list.get(DataUtil.curPosition));
					finalProgress.setText(MusicUntil.formatTime(DataUtil.list
							.get(DataUtil.curPosition).getDuration()));
					playMusic.setBackgroundResource(R.drawable.play_selector);
					isPause = false;
					DataUtil.isPlaying = false;
				}
			}
		}
	}

}
